package NetWorkTest1;

import java.io.IOException;
import java.net.*;
import java.util.Scanner;

public class UdpClient {
    DatagramSocket socket = null;
    //客户端不需要指定端口号
    //实例化DatagramSocket就在操作系统内核打开了socket文件--可以进行收发数据
    public  UdpClient() throws SocketException {
        socket = new DatagramSocket();
    }

    public void start() throws IOException {
        System.out.println("客户端启动!!!");
        while(true){
            //用户需要输入信息---构造请求
            Scanner scanner = new Scanner(System.in);
            System.out.print(">");
            String request = scanner.next();
            //以数据报的形式发送请求
            //构造成一个数据报
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(),
                    request.getBytes().length,
                    InetAddress.getByName("127.0.0.1"),8000);
            //将数据报发送给服务器
            socket.send(requestPacket);
            //根据服务器的响应--客户端接收服务器的响应
            DatagramPacket responsePacket = new DatagramPacket(new byte[4096]
                    ,4096);
            socket.receive(responsePacket);
            //将数据报转化成字符串
            String response = new String(responsePacket.getData(),0,
                    responsePacket.getLength());
            System.out.printf("req = %s ; rep = %s\n",request,response);
        }
    }

    public static void main(String[] args) throws IOException {
        UdpClient udpClient = new UdpClient();
        udpClient.start();
    }
}
